<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
  >
  <el-alert
    title="若已存在商品名称、销售属性值相同的记录，则会覆盖原记录"
    type="warning"
    effect="dark">
  </el-alert>

    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="80px"
    >
      <el-form-item label="商品名称" prop="productId" label-width="100px">
        <!-- <el-input v-model="dataForm.productId" placeholder="商品ID"></el-input> -->
        <el-select
          filterable
          v-model="dataForm.productId"
          placeholder="请选择商品"
          @change="clearExtraPrice"
        >
          <el-option
            v-for="item in productList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="销售属性名" prop="saleAttrName" label-width="100px">
        <!-- <el-input v-model="dataForm.saleAttrId" placeholder="销售属性ID"></el-input> -->
        <el-select
          filterable
          v-model="selectedSaleAttrName"
          placeholder="请选择销售属性名"
          @change="handleSelectedSaleAttrNameChange"
        >
          <el-option
            v-for="item in SaleAttrNames"
            :key="item"
            :label="item"
            :value="item"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="销售属性值" prop="saleAttrId" label-width="100px">
        <!-- <el-input v-model="dataForm.saleAttrId" placeholder="销售属性ID"></el-input> -->
        <el-select
          filterable
          v-model="dataForm.saleAttrId"
          placeholder="请选择销售属性值"
          @change="handleSelectedSaleAttrIdChange"
        >
          <el-option
            v-for="item in saleAttrs"
            :key="item.id"
            :label="item.attrValue"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="额外价格" prop="extraPrice" label-width="100px">
        <el-input
          v-model="dataForm.extraPrice"
          placeholder="额外价格"
        ></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  data () {
    return {
      selectedSaleAttrName: '',
      productList: [],
      SaleAttrNames: [],
      saleAttrs: [],
      visible: false,
      dataForm: {
        id: 0,
        productId: '',
        saleAttrId: '',
        extraPrice: ''
      },
      dataRule: {
        productId: [
          { required: true, message: '商品不能为空', trigger: 'blur' }
        ],
        saleAttrId: [
          { required: true, message: '销售属性值不能为空', trigger: 'blur' }
        ],
        extraPrice: [
          { required: true, message: '额外价格不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 清除 额外价格
    clearExtraPrice () {
      this.dataForm.extraPrice = ''
    },
    // 处理 选择的销售属性值 变化
    async handleSelectedSaleAttrIdChange (saleAttrId) {
      this.clearExtraPrice()
      console.log('选择的销售属性id', saleAttrId)
      let existProductSaleAttrRelation = await this.queryByProductIdAndSaleAttrId(this.dataForm.productId, saleAttrId)
      // 如果 属性id、商品id 已经存在关联，则回显价格
      if (existProductSaleAttrRelation) {
        console.log('已经存在关联', existProductSaleAttrRelation)
        this.dataForm.extraPrice = existProductSaleAttrRelation.extraPrice
      }
    },
    // 根据销售属性id、商品id，查询 关联信息
    async queryByProductIdAndSaleAttrId (productId, saleAttrId) {
      let result
      this.dataListLoading = true

      await this.$http({
        url: this.$http.adornUrl(`/productsaleattrrelation/info?productId=${productId}&saleAttrId=${saleAttrId}`),
        method: 'get'
      }).then(({ data }) => {
        if (data && data.code === 0) {
          result = data.data
        }
        this.dataListLoading = false
      })

      return result
    },
    // 处理 选择的销售属性名 变化
    handleSelectedSaleAttrNameChange (name) {
      this.clearExtraPrice()

      this.dataForm.saleAttrId = ''
      this.getSaleAttrByName(name)
    },
    // 通过销售属性名 获取 销售属性
    getSaleAttrByName (name) {
      console.log(name)
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrl('/saleattr/getbyname?name=' + name),
        method: 'get'
      }).then(({ data }) => {
        console.log(data)
        if (data && data.code === 0) {
          this.saleAttrs = data.list
        } else {
          this.saleAttrs = []
        }
        this.dataListLoading = false
      })
    },
    // 获取所有商品
    getProductList () {
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrl('/product/all'),
        method: 'get'
      }).then(({ data }) => {
        console.log(data)
        if (data && data.code === 0) {
          this.productList = data.list
        } else {
          this.productList = []
        }
        this.dataListLoading = false
      })
    },
    // 获取所有销售属性名称
    getSaleAttrNames () {
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrl('/saleattr/all/name'),
        method: 'get'
      }).then(({ data }) => {
        console.log(data)
        if (data && data.code === 0) {
          this.SaleAttrNames = data.list
        } else {
          this.SaleAttrNames = []
        }
        this.dataListLoading = false
      })
    },
    init (id) {
      this.dataForm.id = id || 0
      this.visible = true
      //
      this.getProductList()
      this.getSaleAttrNames()

      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(
              `//productsaleattrrelation/info/${this.dataForm.id}`
            ),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.dataForm.productId = data.productSaleAttrRelation.productId
              this.dataForm.saleAttrId =
                data.productSaleAttrRelation.saleAttrId
              this.dataForm.extraPrice =
                data.productSaleAttrRelation.extraPrice
              // 回显
              this.selectedSaleAttrName =
                data.productSaleAttrRelation.saleAttrName
              if (this.selectedSaleAttrName) {
                this.getSaleAttrByName(this.selectedSaleAttrName)
              }
            }
          })
        }
      })
    },
    // 表单提交
    dataFormSubmit () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(
              `//productsaleattrrelation/${
                !this.dataForm.id ? 'save' : 'update'
              }`
            ),
            method: 'post',
            data: this.$http.adornData({
              id: this.dataForm.id || undefined,
              productId: this.dataForm.productId,
              saleAttrId: this.dataForm.saleAttrId,
              extraPrice: this.dataForm.extraPrice
            })
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })
    }
  }
}
</script>
